package com.iskyline.demo.leetcode;

import java.util.Arrays;
import java.util.Hashtable;

/**
 * @author iskyline
 * @version 11
 * @createTime 2023年11月06日 21:23:00
 */
public class Solution001 {

    /**
     * 方法一：暴力枚举
     * 时间复杂度：O(n²)
     * 空间复杂度：O(1)
     * @param nums
     * @param target
     * @return
     */
    public int[] twoSumAll(int[] nums, int target) {
        int[] result = new int[2];
        for(int i=0;i<nums.length;i++){
            for(int j=i+1;j<nums.length;j++){
                System.out.println("i="+i+","+nums[i]);
                System.out.println("j="+j+","+nums[j]);
                if(nums[i]+nums[j]==target){
                    result[0] = i;
                    result[1] = j;
                    return result;
                }
            }
        }
        return result;
    }

    /**
     * 方法二：hash方法
     * 弊端：如果数组中两个数相同，则无法查找出来
     * @param nums
     * @param target
     * @return
     */
    public int[] twoSumHash(int[] nums, int target){
        Hashtable<Integer,Integer> resultRange = new Hashtable<>();
        for (int i = 0; i < nums.length; i++) {
            if(null!=resultRange.get(target - nums[i])){
                return new int[]{resultRange.get(target - nums[i]),i};
            }
            resultRange.put(nums[i],i);
        }
        return new int[]{0};
    }



    public static void main(String[] args) {
        Solution001 solution001 = new Solution001();
        //System.out.println(Arrays.toString(solution001.twoSum(new int[]{2,7,11,15},9)));
        //System.out.println(Arrays.toString(solution001.twoSum(new int[]{3,2,4},6)));

        //System.out.println(Arrays.toString(solution001.twoSumHash(new int[]{2,7,11,15},9)));
        System.out.println(Arrays.toString(solution001.twoSumHash(new int[]{3,3},6)));
    }

}
